<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Basic;
use App\Models\Collect;
use App\Models\Comments;
use App\Models\ComTags;
use App\Service\BlackWord;
use App\Models\ArticleTags;
use Encore\Admin\Grid\Filter\In;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;

class ArticleController extends BaseController
{
    //获取文章列表
    public function getList()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $category_id = isset($input['category_id']) && is_numeric($input['category_id']) ? $input['category_id'] : '';

        //分页
        $page = isset($input['page']) && $input['page']>1 ? $input[
            'page'] : 1;
        $page_size = isset($input['pagesize']) && $input['pagesize']>1 ? $input[
        'pagesize'] : 10;
        $page_var = ($page-1) * $page_size;
        $model = Article::select('id','cate_id','title','intro','pic','source_link','status','created_at','views','from_cateid','content','comments_num','play_time','from_author');
        if($category_id){
            $model = $model->where('cate_id', $category_id);
        }
        $total = $model
            ->where('status',1)
            ->orderby('created_at','desc')
            ->count();
        $total = ceil($total/$page_size);
        $list = $model
            ->where('status', 1)
            ->skip($page_var)
            ->take($page_size)
            ->orderby('created_at','desc')
            ->get();
        foreach ($list as $k => $v){
            $v->date = date('m',strtotime($v->created_at)).'/'.date('d',strtotime($v->created_at));
        }
        if(!empty($list)) {
            $list = array_values($list->toArray());
            shuffle($list);
        }else{
            $list = [];
        }

        return $this->success('成功', ['data'=>$list, 'total'=>$total]);
    }

    /**
     *  增加流浪量
     */
    public function addViews()
    {
        $input = Input::all();

        if(isset($input['article_id']) && is_numeric($input['article_id'])) {
            $res = Article::find($input['article_id'])->increment('views', 1);
            if($res) {
                return $this->success('成功');
            }else{
                return $this->error('失败');
            }
        }else{
            return $this->error('没有文章id');
        }
    }

    //添加收藏
    public function addCollect()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        if(isset($input['article_id']) && is_numeric($input['article_id'])) {
            if($input['types']) {
                $insert = [
                    'member_id' => $member_info['id'],
                    'article_id' => $input['article_id']
                ];
                try {
                    $res = Collect::create($insert);
                }catch (\Exception $e) {
                    $res = false;
                }
            }else{
                try {
                    $res = Collect::where('member_id',$member_info['id'])->where('article_id', $input['article_id'])->delete();
                }catch (\Exception $e) {
                    $res = false;
                }
            }
            if($res) {
                return $this->success('成功');
            }else{
                return $this->error('失败');
            }
        }else{

            return $this->error('没有文章id');
        }
    }

    //获取收藏
    public function getCollect()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        //分页
        $page = isset($input['page']) && $input['page']>1 ? $input[
        'page'] : 1;
        $page_size = isset($input['pagesize']) && $input['pagesize']>1 ? $input[
        'pagesize'] : 10;
        $page_var = ($page-1) * $page_size;

        $list = Collect::select('id','member_id','created_at','article_id')
            ->with(['g_article'=>function($querty){
                return $querty->select('id','title','views','pic','cate_id','source_link','from_cateid','play_time');
            }])
            ->where('member_id', $member_info['id'])
            ->take($page_size)
            ->skip($page_var)
            ->orderby('created_at','desc')
            ->get();
        foreach ($list as $k=>$v) {
            if($v->g_article->from_cateid == 1) {
                $v->g_article->source_link = $this->ixiguaHandle($v->g_article->source_link);
            }else{
                preg_match('/(http|https)/',$v->g_article->source_link, $arr);
                if(empty($arr)){
                    $file = public_path().'/'.$v->g_article->source_link;
                    $vtime = exec("/usr/local/ffmpeg/bin/ffmpeg -i ".$file." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
                    $vtime = explode('.',$vtime);
                    $v->g_article->play_time = $vtime[0];
                    $v->g_article->source_link = $this->http_url.$v->g_article->source_link;
                }
            }
            $v->g_article->isTouchMove = false;
        }

        return $this->success('成功', $list);
    }

    //删除收藏
    public function delCollect()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        if(isset($input['collect_id']) && is_numeric($input['collect_id'])) {
            $res = Collect::find($input['collect_id']);
            if($res){
                if($res['member_id'] == $member_info['id']){
                    $model = Collect::find($input['collect_id'])->delete();
                    if($model){
                        return $this->success("成功");
                    }else{
                        return $this->error("删除失败");
                    }
                }else{
                    return $this->error("无法删除别人的收藏文章");
                }
            }else{
                return $this->error("错误收藏id");
            }
        }else{
            return $this->error("无效收藏id");
        }
    }

    //获取时间
    public function djs()
    {
        $config = Basic::where('keyword', 'djs')->first();
        $s = $config->val * 60;

        return $this->success('成功', ['djs' => $s]);
    }

    //详情页转发图片
    public function getImage()
    {
        $input = Input::all();
        if(isset($input['article_id']) && $input['article_id'] > 0) {
            $article_info = Article::find($input['article_id']);
            $file = file_get_contents($article_info->pic);
            header('Content-type: image/png');

            echo $file;
        }else{
            return $this->error('失败', '参数错误');
        }
    }

    //增加评论
    public function addComment()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $content = isset($input['content'])&&!empty($input['content']) ? $input['content'] : '';
        if(!empty($content)){
            $content = (new BlackWord())->searchReplace($content);
        }
        if(isset($input['article_id']) && is_numeric($input['article_id'])){
            $insert = [
                'article_id' => $input['article_id'],
                'member_id' => $member_info['id'],
                'content' => $content,
                'date' => date('Y-m-d H:i:s',time())
            ];
            if(isset($input['comment_id']) && !empty($input['comment_id'])){
                $insert['comment_id'] = $input['comment_id'];
            }
            DB::beginTransaction();
            try {
                $res = Article::find($input['article_id'])->increment('comments_num');
                $model = Comments::create($insert);
            }catch (\Exception $e) {
                DB::rollBack();
                return $this->error('评论失败');
            }
            DB::commit();
            $sql = Comments::select('id', 'member_id', 'content', 'date', 'zan')
                ->with(['g_member'=>function($querty){
                    return $querty->select('id', 'name', 'avatar');
                }])
                ->find($model->id);
            $sql['isSelfTag'] = 0;
            if($model){
                return $this->success('评论成功', $sql);
            }
        }else{
            return $this->error('没有文章id');
        }
    }

    //文章详情
    public function getDetail()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $page = isset($input['page']) && $input['page']>1 ? $input[
        'page'] : 1;
        $page_size = isset($input['pagesize']) && $input['pagesize']>1 ? $input[
        'pagesize'] : 10;
        $page_var = ($page-1) * $page_size;
        if(isset($input['article_id']) && $input['article_id'] > 0){
            try{
                $model = Article::select('id','cate_id','title','intro','pic','source_link','status','created_at','views','from_cateid','content','comments_num','play_time','from_author','zan');
                $res = $model
                    ->with(['g_collect'=>function($query) use($member_info){
                        return $query->where('member_id', $member_info['id'])
                        ->select('id','member_id','article_id');
                    }])
                    ->find($input['article_id']);
                if(!empty($res->g_collect)) {
                    $res->is_collect = 1;
                }else{
                    $res->is_collect = 0;
                }
                $art_tag = ArticleTags::select()
                    ->where('article_id', $input['article_id'])
                    ->where('member_id', $member_info['id'])
                    ->first();
                if($art_tag){
                    $res['isSelfTag'] = 1;
                }else{
                    $res['isSelfTag'] = 0;
                }
                //评论列表
                $comments_list = Comments::select('id', 'member_id', 'content', 'date', 'zan')
                    ->with(['g_member'=>function($querty){
                        return $querty->select('id', 'name', 'avatar');
                    }])
                    ->where('article_id', $input['article_id'])
                    ->where('status', 0)
                    ->where('comment_id',0)
                    ->take($page_size)
                    ->skip($page_var)
                    ->orderBy('date', 'desc')
                    ->get();
                $total = Comments::where('article_id', $input['article_id'])
                    ->where('status', 0)
                    ->where('comment_id',0)
                    ->count();
                $total = ceil($total/$page_size);
                $arr = [];
                if($comments_list){
                    foreach ($comments_list as $k=>$v){
                        array_push($arr,$v->id);
                        $v->isSelfTag = 0;
                    }
                }
                //回复评论
                $back_comments = Comments::select('id', 'member_id', 'comment_id', 'content', 'date', 'zan')
                    ->with(['g_member'=>function($querty){
                        return $querty->select('id', 'name', 'avatar');
                    }])
                    ->where('article_id', $input['article_id'])
                    ->where('status', 0)
                    ->whereIn('comment_id',$arr)
                    ->orderBy('date', 'desc')
                    ->get()->toArray();
                $arr1 = [];
                if($back_comments){
                    foreach ($back_comments as $k=>&$v) {
                        $v['isSelfTag'] = 0;
                        array_push($arr1, $v['id']);
                    }
                }
                $arr = array_merge($arr,$arr1);
                $com_res = ComTags::select('comment_id')
                    ->whereIn('comment_id', $arr)
                    ->where('member_id', $member_info['id'])
                    ->get();
                $com_id = [];
                if($com_res){
                    foreach ($com_res as $k=>$v){
                        array_push($com_id,$v->comment_id);
                    }
                }
                $comments_list = $comments_list->toArray();
                foreach ($comments_list as $k=>&$v){
                    if(in_array($v['id'], $com_id)){
                        $v['isSelfTag'] = 1;
                    }
                    $array = [];
                    foreach ($back_comments as $kk=>&$vv){
                        if($vv['comment_id'] == $v['id']){
                             $array[$kk] = $back_comments[$kk];
                        }
                        if(in_array($vv['id'], $com_id)){
                            $vv['isSelfTag'] = 1;
                        }
                    }
                    $v['back_comments'] = $array;
                }
                return $this->success("成功", ['detail'=>$res, 'comments'=>$comments_list, 'total' => $total]);
            }catch (\Exception $e) {
                return $this->error("获取详情失败");
            }
        }else{
            return $this->error("无效文章id");
        }
    }

    //评论点赞
    public function comTags()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        if (isset($input['comment_id']) && $input['comment_id'] > 0) {
            $sql = ComTags::select()
                ->where('comment_id', $input['comment_id'])
                ->where('member_id', $member_info['id'])
                ->first();
            if(!$sql){
                try{
                    $insert = [
                        'comment_id' => $input['comment_id'],
                        'member_id' => $member_info['id'],
                        'date' => date('Y-m-d H:i:s')
                    ];
                    $model = Comments::find($input['comment_id'])->increment('zan');
                    $res = ComTags::create($insert);
                    return $this->success('点赞成功',1);
                }catch (\Exception $e){
                    return $this->error('点赞失败');
                }
            }else{
                try{
                    $model = Comments::find($input['comment_id'])->decrement('zan');
                    $res = ComTags::where('comment_id', $input['comment_id'])->where('member_id', $member_info['id'])->delete();
                    return $this->success('取赞成功',0);
                }catch (\Exception $e){
                    return $this->error('取赞失败');
                }
            }
        }else{
            return $this->error('无效评论id');
        }
    }

    //文章点赞
    public function artTags()
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        if (isset($input['article_id']) && $input['article_id'] > 0) {
            $sql = ArticleTags::select()
                ->where('article_id', $input['article_id'])
                ->where('member_id', $member_info['id'])
                ->first();
            if(!$sql){
                try{
                    $insert = [
                        'article_id' => $input['article_id'],
                        'member_id' => $member_info['id'],
                        'date' => date('Y-m-d H:i:s')
                    ];
                    $model = Article::find($input['article_id'])->increment('zan');
                    $res = ArticleTags::create($insert);
                    return $this->success('点赞成功',1);
                }catch (\Exception $e){
                    return $this->error('点赞失败');
                }
            }else{
                try{
                    $model = Article::find($input['article_id'])->decrement('zan');
                    $res = ArticleTags::where('article_id', $input['article_id'])->where('member_id', $member_info['id'])->delete();
                    return $this->success('取赞成功',0);
                }catch (\Exception $e){
                    return $this->error('取赞失败');
                }
            }
        }else{
            return $this->error('无效文章id');
        }
    }

    //删除评论
    public function delComment(Request $request)
    {
        $input = Input::all();
        $member_info = $this->getMemberBy3rd($input['_3rd_session']);
        $validator = Validator::make($request->all(), [
            'article_id' => 'required',
            'member_id' => 'required',
            'comment_id' => 'required',
        ]);
        if ($validator->fails()) {
            return $validator->errors();
        }
        if ($input['member_id'] == $member_info['id']) {
//            DB::beginTransaction();
            try{
                $res = Comments::find($input['comment_id']);
                if($res){
                    $sql = Article::find($input['article_id'])->decrement('comments_num');
                    $res->status = 1;
                    $res->save();
                }else{
                    return $this->error("错误评论id");
                }
                return $this->success('删除成功');
            }catch (\Exception $e) {
//                DB::rollBack();
                return $this->error("删除评论失败");
            }
//            DB::commit();
        }else {
            return $this->error("无法删除其他用户的评论");
        }
    }
}
